package cn.edu.zjicm.wordsnet_d.download;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import cn.edu.zjicm.wordsnet_d.R;
import cn.edu.zjicm.wordsnet_d.activity.SettingActivity;
import cn.edu.zjicm.wordsnet_d.datapersistent.FileManager;
import cn.edu.zjicm.wordsnet_d.net.Client;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.RemoteViews;

public class UpdateService extends Service {
	private Notification notification;
	private NotificationManager nManager;
	private static final int NOTIFICATION_ID = 1;
	private Thread downLoadThread;

	private StringBuilder sb;// 这个是更新版本时显示进度用
	private int numread;
	private InputStream is;
	private byte buf[];
	private int progress, length, count; // length是新版本的总大小，count是已下载的大小
	private static final int DOWN_UPDATE = 2;
	private static final int DOWN_OVER = 3;
	private boolean interceptFlag = false;
	private static ExecutorService eService = Executors.newFixedThreadPool(10);//固定5个线程来执行任务
	Handler mHandler = new Handler(){
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case DOWN_UPDATE:
				/*
				 * updateProgressBar.setProgress(progress);
				 * updateProgressText.setText((String)msg.obj);
				 */
				notification.contentView = new RemoteViews(getApplication().getPackageName(), R.layout.remotesview);
				notification.contentView.setProgressBar(R.id.pb, 100,
						progress, false);
				notification.contentView.setTextViewText(R.id.tv,
						(String) msg.obj);
				nManager.notify(NOTIFICATION_ID, notification);// 这是再更新
				break;
			case DOWN_OVER:
				nManager.cancel(NOTIFICATION_ID);
				//mUpdateAskWindow.dismiss();
				installApk();
				UpdateManager.showWindowFlag = true;
				break;
			}
		};
	};
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		System.out.println("进入UpdateService");
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub
		nManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
		notification = new Notification(R.drawable.download, "更新版本中...",
				System.currentTimeMillis());
		notification.flags = Notification.FLAG_AUTO_CANCEL;
		
		notification.contentIntent = PendingIntent.getActivity(
				this, 0, new Intent(this,
						SettingActivity.class), 0);
		notification.contentView = new RemoteViews(getApplication().getPackageName(), R.layout.remotesview);
		notification.contentView.setProgressBar(R.id.pb, 100, 0, false);
		notification.contentView.setTextViewText(R.id.tv, "");
		nManager.notify(NOTIFICATION_ID, notification);
		downloadApk();
		return super.onStartCommand(intent, flags, startId);
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}
	/**
	 * 下载apk
	 * 
	 * @param url
	 */

	public void downloadApk() {
		System.out.println("进入downloadApk");
		//downLoadThread = new Thread(mdownApkRunnable);
		//downLoadThread.start();
		startDownload();
	}
	private void startDownload() {
		// TODO Auto-generated method stub
		eService.execute(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					URL url = new URL(Client.BASE_URL + UpdateManager.apkFileName);

					HttpURLConnection conn = (HttpURLConnection) url
							.openConnection();
					conn.connect();
					length = conn.getContentLength();
					is = conn.getInputStream();

					File file = new File(FileManager.DOWNLOAD_PATH);
					if (!file.exists()) {
						file.mkdir();
					}
					String apkFile = FileManager.DOWNLOAD_PATH + UpdateManager.apkFileName;
					File ApkFile = new File(apkFile);
					FileOutputStream fos = new FileOutputStream(ApkFile);

					count = 0;
					buf = new byte[1024];
					do {
						getProgressNum();
						Message msg = Message.obtain(mHandler, DOWN_UPDATE,
								sb.toString());
						// 更新进度
						mHandler.sendMessage(msg);
						if (numread <= 0) {
							// 下载完成通知安装
							mHandler.sendEmptyMessage(DOWN_OVER);
							break;
						}
						fos.write(buf, 0, numread);
					} while (!interceptFlag);// 点击取消就停止下载.

					fos.close();
					is.close();
				   System.out.println("在下载的线程中");
				} catch (MalformedURLException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		});
	}
	/*private Runnable mdownApkRunnable = new Runnable() {
		@Override
		public void run() {
			

		}
	};*/
	/**
	 * 得到下载新版本的进度
	 */
	private void getProgressNum() {
		try {
			numread = is.read(buf);
			count += numread;
			progress = (int) (((float) count / length) * 100);
			// mHandler.sendEmptyMessage(DOWN_UPDATE);
			sb = new StringBuilder();
			sb.append(count / 1024).append("KB/").append(length / 1024)
					.append("KB");
			progress = (int) (((float) count / length) * 100);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/**
	 * 安装apk
	 * 
	 * @param url
	 */
	private void installApk() {
		File apkfile = new File(FileManager.DOWNLOAD_PATH + UpdateManager.apkFileName);
		if (!apkfile.exists()) {
			return;
		}

		Intent i = new Intent();
		i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		i.setAction(Intent.ACTION_VIEW);
		i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
				"application/vnd.android.package-archive");
		startActivity(i);
		SettingActivity.notifyFlag = false;
		System.out.println("运行到installApk中notifyFlag=" + SettingActivity.notifyFlag);
	}
}
